import axios, { type AxiosRequestConfig } from "axios";

const axiosInstance = axios.create({
  timeout: 10 * 60 * 1000,
  headers: {
    "Content-Type": "application/json",
  },
});

axiosInstance.interceptors.request.use((config) => {
  const method = config.method!.toUpperCase();
  // 兼容params和data参数
  if (["GET", "DELETE"].includes(method)) {
    config.params = config.params || config.data;
  } else if (["POST", "PUT"].includes(method)) {
    config.data = config.data || config.params;
    delete config.params;
  }
  // 兼容url前缀
  if (!config.url?.startsWith("http") && !config.url?.startsWith("/nest/")) {
    config.url = "/soft" + config.url;
  }
  // token
  const token = localStorage.getItem("token");
  config.headers["X-Access-Token"] = token;
  return config;
});
axiosInstance.interceptors.response.use(
  (response) => {
    if ([0, 200].includes(response.data.code)) {
      return response.data.result;
    }
    return Promise.reject(response.data);
  },
  ({ response }) => {
    return Promise.reject(response.data);
  }
);

const requestFn = (config: AxiosRequestConfig = {}) => {
  return (method?) => {
    return axiosInstance.request({
      method,
      ...config,
    });
  };
};

export const defHttp = {
  get(config: AxiosRequestConfig) {
    return requestFn(config)("GET");
  },
  post(config: AxiosRequestConfig) {
    return requestFn(config)("POST");
  },
  put(config: AxiosRequestConfig) {
    return requestFn(config)("PUT");
  },
  delete(config: AxiosRequestConfig) {
    return requestFn(config)("DELETE");
  },
  request(config: AxiosRequestConfig) {
    return requestFn(config)();
  },
  setHeader(headers: any): void {
    Object.assign(axiosInstance.defaults.headers, headers);
  },
};
